let wxRequest = require('./utils/request').wxRequest()
const {API_OK} = require('./utils/setting')
App({
  onLaunch: function () {
    wx.clearStorage()
    this.getSystemInfo()

    // 登录
    wx.login({
      success: async res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        // console.log(res)
        if (res.errMsg === 'login:ok') {
          this.globalData.code = res.code
          try {
            const response = await wxRequest.post({ url: '/api/login', data: { code: res.code } })
            // console.log(response)
            if (response.code === API_OK) {
              wx.setStorageSync('token', response.data.token)
              this.tokenReadyCallback && this.tokenReadyCallback()
            } else {
              this.getTokenFailedCallback && this.getTokenFailedCallback()
            }
          } catch(err) {
            console.warn(err)
            this.getTokenFailedCallback && this.getTokenFailedCallback()
          }
        }
      }
    })
    // 获取用户信息
    wx.getSetting({
      success: res => {
        // console.log(res.authSetting)
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
          wx.getUserInfo({
            success: res => {
              // 可以将 res 发送给后台解码出 unionId
              this.globalData.userInfo = res.userInfo
              // console.log(res.userInfo)

              // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
              // 所以此处加入 callback 以防止这种情况
              if (this.userInfoReadyCallback) {
                this.userInfoReadyCallback(res)
              }
            }
          })
        }
      }
    })
  },
  globalData: {
    code: null,
    userInfo: null,
    headerHeight: 0,
    headerPaddingTop: 10,
    viewportWidth: 375
  },
  getSystemInfo() {
    const {top, bottom} = wx.getMenuButtonBoundingClientRect()
    wx.getSystemInfo({
      success: ({statusBarHeight, screenWidth})=>{
        this.globalData.headerHeight = bottom + (top - statusBarHeight)
        this.globalData.headerPaddingTop = statusBarHeight
        this.viewportWidth = screenWidth
      }
    })
  },
  /**
   * 获取 globalData 中的值
   * @param {string} property globalData 中的属性名
   */
  getGlobalData(property) {
    return this.globalData[property]
  }
})
